const Cart = require('../../utils/cart.js');

Page({
  data: {
    cartItems: [],
    totalPrice: 0
  },

  onLoad() {
    this.loadCartItems();
  },

  onShow() {
    this.loadCartItems();
  },

  loadCartItems() {
    const cartItems = Cart.getCart();
    const totalPrice = Cart.getTotalPrice();
    
    this.setData({
      cartItems,
      totalPrice
    });
  },

  decreaseQuantity(e) {
    const productId = e.currentTarget.dataset.id;
    Cart.decreaseQuantity(productId);
    this.loadCartItems();
  },

  increaseQuantity(e) {
    const productId = e.currentTarget.dataset.id;
    Cart.increaseQuantity(productId);
    this.loadCartItems();
  },

  removeFromCart(e) {
    const productId = e.currentTarget.dataset.id;
    Cart.removeFromCart(productId);
    this.loadCartItems();
  },

  goToCheckout() {
    wx.navigateTo({
      url: '/pages/checkout/checkout'
    });
  },

  goToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  async payOrder() {
    if (this.data.cartItems.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      });
      return;
    }

    try {
      wx.showLoading({
        title: '创建订单中...'
      });

      const api = require('../../utils/request.js');
      const userId = wx.getStorageSync('userId') || 1;
      
      // 构建订单数据
      const orderData = {
        userId: userId,
        paymentMethod: 2, // 2-微信支付（根据后端定义：1-现金，2-微信，3-支付宝）
        items: this.data.cartItems.map(item => ({
          productId: item.id,
          quantity: item.quantity
        }))
      };

      // 调用创建订单接口
      const result = await api.createOrder(orderData);
      
      wx.hideLoading();
      
      if (result.code === 200 && result.data) {
        // 清空购物车
        Cart.clearCart();
        
        wx.showToast({
          title: '订单创建成功',
          icon: 'success',
          duration: 1500
        });

        // 跳转到订单详情页面
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/orderDetail/orderDetail?orderNo=${result.data.orderNo}`
          });
        }, 1500);
      } else {
        wx.showToast({
          title: result.message || '创建订单失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('创建订单失败:', error);
      wx.showToast({
        title: '创建订单失败，请重试',
        icon: 'none'
      });
    }
  }
});